package com.ghck.server.security;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import com.ghck.server.exception.GhckException;
import com.ghck.server.exception.ErrorConstant;
import com.ghck.server.model.AjkAccount;
import com.ghck.server.model.UserRole;
import com.ghck.server.service.AjkAccountService;

@Component("userDetailsService")
public class AjkUserDetailsService implements UserDetailsService {

	@Autowired
    private AjkAccountService ajkAccountService;

	@Override
    public AjkUserDetails loadUserByUsername(String accessId){
       
    	AjkAccount builder = ajkAccountService.findByAccessId(accessId);
            
        if (builder == null) {
            throw new GhckException(ErrorConstant.ACCOUNT_EXPIRED.getErrorCode(),ErrorConstant.ACCOUNT_EXPIRED.getMsg());
        }
        
        Integer userId = builder.getUserId();
        Integer role = builder.getRole();
        UserRole userRole = UserRole.fromInt(role);	
        String userName = builder.getAccessId();
        String accessKey = builder.getAccessKey();
        Date accountExpiredTime = builder.getAccountExpiredTime();
        GrantedAuthority authority = new SimpleGrantedAuthority(userRole.name());
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(authority);
        AjkUserDetails details = new AjkUserDetails(authorities, userId, userName, accessKey, accountExpiredTime);
        
        return details;
    }
}
